<?php

namespace App\Http\Controllers;

use App\Models\CategoryModel;
use App\Services\CategoryService;
use Illuminate\Http\Request;

class CategoryController extends BaseController {

    public function index(Request $request) {
        return view("category.index", $this->view_data);
    }

    public function list(Request $request) {
        $params = $request->all();

        $list = (new CategoryService())->list($params);

        return $this->apiSuccess($list);
    }


    public function create(Request $request) {
        $info_id = $request->get("info_id", 0);
        $info = [];
        if (!empty($info_id)) {
            $info = (new CategoryService())->info($info_id);
        }
        $this->view_data['info'] = $info;

        return view('category.add', $this->view_data);
    }

    public function save(Request $request) {
        $info_id = $request->post('info_id', 0);
        $title = $request->post('title', '');
        $images = $request->post('images', null);
        if (empty($info_id)) {
            $model = new CategoryModel();
        }else{
            $model = CategoryModel::find($info_id);
        }
        $model->class_name = $title;
        $model->images = json_decode($images, true);
        $model->save();
        if (!$model->id){
            return $this->apiError('保存失败');
        }
        return $this->apiSuccess('','保存成功');
    }

    public function delete(Request $request) {
        $info_id = $request->get("info_id", 0);

        (new CategoryService())->delete($info_id);

        return $this->apiSuccess('ok');
    }

}